from django.db import models
from django.forms.models import model_to_dict
from django.db.models.query import QuerySet

class DateTimeAwareQuerySet(QuerySet):
    def iterator(self, result_class=None):
        for obj in super().iterator(result_class=result_class):
            for field in obj._meta.get_fields():
                print(field)
                if isinstance(getattr(obj, field.name, None), (models.datetime.datetime, models.date.date)):
                    setattr(obj, field.name, getattr(obj, field.name).strftime('%Y-%m-%d %H:%M:%S'))
            yield obj

class MyModelManager(models.Manager):
    def get_queryset(self):
        return DateTimeAwareQuerySet(self.model, using=self._db)


class BaseModel(models.Model):
    # objects = MyModelManager() # 似乎并没有作用

    class Meta:
        abstract = True

    def to_dict(self, fields=None, exclude=None):
        return model_to_dict(self, fields, exclude)

    def to_json(self):
        str_fields = []
        file_fields = []

        for field in self._meta.fields:
            if isinstance(field, (models.FileField, models.ImageField)):
                file_fields.append(field.name)
            else:
                str_fields.append(field.name)

        data = model_to_dict(self, str_fields)
        for filed in file_fields:
            file = getattr(self, filed)
            if file:
                data[filed] = file.url
            else:
                data[filed] = ''
        return data

